﻿using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using WeatherData;

namespace ATCAssistant
{
    public class Station
    {
        private XElement root;

        public static Station Open(string stationDefinitionPath)
        {
            return new Station(XElement.Load(stationDefinitionPath));
        }

        public string Identifier { get; private set; }
        public string Name { get; private set; }
        public List<Runway> Runways { get; private set; }
        public List<Frequency> Communications { get; private set; }
        public List<Restriction> Restrictions { get; private set; }
        

        private Station(XElement stationRoot)
        {
            this.root = stationRoot;
            this.Identifier = this.root.Attribute("id").Value;
            this.Name = this.root.Element("name").Value;
            this.LoadRunways();
            this.LoadCommunications();
            this.LoadRestrictions();
        }

        public Metar GetCurrentMetar()
        {
            return new Metar(this.Identifier);
        }

        private void LoadRunways()
        {
            IEnumerable<XElement> runwayCollection = from rwy in this.root.Descendants("runway")
                                                     select rwy;
            this.Runways = new List<Runway>();
            foreach (XElement r in runwayCollection)
                this.Runways.Add(new Runway(r));
        }
        private void LoadCommunications()
        {
            IEnumerable<XElement> commsCollection = from comm in this.root.Descendants("frequency")
                                                    select comm;
            this.Communications = new List<Frequency>();
            foreach (XElement comm in commsCollection)
                this.Communications.Add(new Frequency(comm));
        }
        private void LoadRestrictions()
        {
            IEnumerable<XElement> restCollection = from rest in this.root.Descendants("restriction")
                                                   select rest;
            this.Restrictions = new List<Restriction>();
            foreach (XElement rest in restCollection)
                this.Restrictions.Add(new Restriction(rest));
        }
    }
}
